/**
 * Copyright (c) 2018 开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.common.xss;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * XSS过滤
 * @author Mark sunlightcs@gmail.com
 */
public class XssFilter implements Filter {
	private List<String> excludes = new ArrayList<>();

	@Override
	public void init(FilterConfig config) {
		String exclusions = config.getInitParameter("exclusions");
		if (StringUtils.isNotBlank(exclusions)) {
			excludes = Arrays.asList(exclusions.split(","));
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		// 检查是否是例外路径
		if (isExcludePath(req.getRequestURI())) {
			chain.doFilter(request, response);
			return;
		}

		XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(
				(HttpServletRequest) request);
		// 否则执行XSS过滤
		chain.doFilter(xssRequest, response);
	}

	@Override
	public void destroy() {
	}

	private boolean isExcludePath(String uri) {
		for (String exclude : excludes) {
			if (uri.startsWith(exclude.trim()) ||
					uri.matches(exclude.trim().replace("*", ".*"))) {
				return true;
			}
		}
		return false;
	}
}
